// PostCreatePage.jsx
import React from 'react';
import { 
  Box, Card, CardContent, TextField, Button, Select, 
  MenuItem, InputLabel, FormControl, Typography, 
  Snackbar, Alert,  // 修改按钮组件
} from '@mui/material';
import { PhotoCamera, VideoCameraBack } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom'; // 引入导航钩子
import LoadingButton from '@mui/lab/LoadingButton'; // 从 @mui/lab 导入

const PostCreatePage = () => {
  const navigate = useNavigate(); // 获取导航函数
  const [content, setContent] = React.useState('');
  const [visibility, setVisibility] = React.useState('public');
  const [mediaFiles, setMediaFiles] = React.useState([]);
  const [loading, setLoading] = React.useState(false); 
  const [openSnackbar, setOpenSnackbar] = React.useState(false); 
  const [snackbarMessage, setSnackbarMessage] = React.useState(''); // 新增消息状态
  const [snackbarSeverity, setSnackbarSeverity] = React.useState('success'); // 新增提示类型

  // 模拟全局存储（实际项目建议使用状态管理或API）
  const [posts, setPosts] = React.useState(
    JSON.parse(localStorage.getItem('posts')) || []
  );

  const handleFileChange = (e) => {
    const files = Array.from(e.target.files);
    setMediaFiles(files);
  };

  const handleSubmit = async () => {
    // 内容验证
    if (content.trim() === '') {
      showSnackbar('内容不能为空', 'error');
      return;
    }

    if (loading) return;
    setLoading(true);

    try {
      // 模拟创建动态数据
      const newPost = {
        id: Date.now(),
        content: content.trim(),
        visibility,
        media: mediaFiles.map(file => ({
          type: file.type.split('/')[0],
          url: URL.createObjectURL(file)
        })),
        timestamp: new Date(),
        user: {
          name: '匿名用户',
          avatar: 'https://via.placeholder.com/40'
        }
      };

      // 更新本地存储
      setPosts([newPost, ...posts]);
      localStorage.setItem('posts', JSON.stringify([newPost, ...posts]));

      // 清空表单
      setContent('');
      setMediaFiles([]);
      setVisibility('public');
      
      showSnackbar('动态发布成功！', 'success');
      
      // 导航回首页
      navigate('/');

    } catch (error) {
      showSnackbar('发布失败：' + error.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  const showSnackbar = (message, severity) => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setOpenSnackbar(true);
  };

  const handleSnackbarClose = (event, reason) => {
    if (reason === 'clickaway') return;
    setOpenSnackbar(false);
  };

  return (
    <Box sx={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
      <Card variant="outlined">
        <CardContent>
          <Typography variant="h6" sx={{ color: '#2c3e50', marginBottom: 2 }}>
            发布动态
          </Typography>

          <TextField
            fullWidth
            multiline
            rows={4}
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="分享你的生活点滴..."
            sx={{ marginBottom: 2 }}
          />

          <Box sx={{ marginBottom: 2 }}>
            <input
              accept="image/*, video/*"
              id="contained-button-file"
              multiple
              type="file"
              onChange={handleFileChange}
              style={{ display: 'none' }}
            />
            <label htmlFor="contained-button-file">
              <Button 
                variant="outlined" 
                component="span" 
                startIcon={<PhotoCamera />} 
                sx={{ marginRight: 2 }}
              >
                上传图片
              </Button>
            </label>
            <label htmlFor="contained-button-file">
              <Button 
                variant="outlined" 
                component="span" 
                startIcon={<VideoCameraBack />}
              >
                上传视频
              </Button>
            </label>
          </Box>

          <FormControl fullWidth sx={{ marginBottom: 2 }}>
            <InputLabel>可见范围</InputLabel>
            <Select
              value={visibility}
              label="可见范围"
              onChange={(e) => setVisibility(e.target.value)}
            >
              <MenuItem value="public">公开</MenuItem>
              <MenuItem value="friends">仅好友</MenuItem>
              <MenuItem value="private">仅自己</MenuItem>
            </Select>
          </FormControl>

          <LoadingButton // 使用LoadingButton组件
            variant="contained"
            color="primary"
            onClick={handleSubmit}
            loading={loading}
            sx={{ textTransform: 'none', width: '100%' }}
          >
            {loading ? '发布中...' : '发布动态'}
          </LoadingButton>
        </CardContent>
      </Card>

      <Snackbar
        open={openSnackbar}
        autoHideDuration={3000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <Alert 
          onClose={handleSnackbarClose} 
          severity={snackbarSeverity}
          sx={{ borderRadius: 2, width: 'fit-content' }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default PostCreatePage;